package com.training.bt.service;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.training.bt.common.PageResponseDTO;
import com.training.bt.entity.DownloadHistory;
import com.training.bt.entity.Resource;
import com.training.bt.entity.User;
import com.training.bt.mapper.DownloadHistoryMapper;
import com.training.bt.mapper.ResourceMapper;
import com.training.bt.security.util.SecurityUtils;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class DownloadHistoryService {
    private final DownloadHistoryMapper downloadHistoryMapper;
    private final ResourceMapper resourceMapper;

    public void newDownloadHistory(Long resourceId) {
        DownloadHistory downloadHistory = new DownloadHistory();
        User user = SecurityUtils.getCurrentUser();
        Resource resource = resourceMapper.selectById(resourceId);

        downloadHistory.setUserId(user.getId());
        downloadHistory.setResourceId(resourceId);
        downloadHistory.setPointsUsed(resource.getPoints());
        downloadHistory.setDownloadTime(LocalDateTime.now());
        downloadHistoryMapper.insert(downloadHistory);
    }

    public PageResponseDTO<DownloadHistory> getDownloadHistoryList(int page, int size) {
        Page<DownloadHistory> request = new Page<>(page, size);
        User user = SecurityUtils.getCurrentUser();
        LambdaQueryWrapper<DownloadHistory> wrapper = new LambdaQueryWrapper<DownloadHistory>()
                .eq(DownloadHistory::getUserId, user.getId());

        Page<DownloadHistory> result = downloadHistoryMapper.selectPage(request, wrapper);
        List<DownloadHistory> HistoryList = request.getRecords();
        return new PageResponseDTO<>(result.getTotal(), HistoryList);
    }

    public boolean isPay(Long userId, Long resourceId) {
        LambdaQueryWrapper<DownloadHistory> wrapper = new LambdaQueryWrapper<DownloadHistory>()
                .eq(DownloadHistory::getUserId, userId)
                .eq(DownloadHistory::getResourceId, resourceId);

        DownloadHistory downloadHistory = downloadHistoryMapper.selectOne(wrapper, false);

        if(downloadHistory==null) return false;
        else return true;
    }

    public Integer exist(Long userId,Long resourceId){
        return downloadHistoryMapper.existsById(userId, resourceId);
    }
}
